import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter_hi_cache/flutter_hi_cache.dart';
import 'package:login/dao/header_util.dart';

import 'package:http/http.dart' as http;
import 'package:login/util/navigator_util.dart';

class LoginDao {
  static const kUserInfo = "user_info";

  static login(String userName, String password) async {
    Map<String, String> paramsMap = {};
    paramsMap["userName"] = userName;
    paramsMap["password"] = password;
    var uri = Uri.https('api.devio.org', '/uapi/user/login', paramsMap);
    final response = await http.post(uri, headers: hiHeaders());
    Utf8Decoder utf8decoder = const Utf8Decoder(); // fix 中文乱码
    String bodyString = utf8decoder.convert(response.bodyBytes);
    debugPrint(bodyString);
    if (response.statusCode == 200) {
      var result = json.decode(bodyString);
      if (result['code'] == 0 && result['data'] != null) {
        Map<String, dynamic> extras = result['extra'];
        // 保存登陆信息
        _saveUserInfo(
          boardingPass: result['data'],
          userName: extras['userName'],
          avatar: extras['avatar'],
          imoocId: extras['imoocId'],
        );
      } else {}
    } else {}
  }

  static void _saveUserInfo({required boardingPass, required userName, required imoocId, required avatar}) {
    var map = {
      'boardingPass': boardingPass,
      'userName': userName,
      'imoocId': imoocId,
      'avatar': avatar,
      'accountHash': userName.hashCode,
    };
    HiCache.getInstance().setString(kUserInfo, jsonEncode(map));
  }

  static Map<String, dynamic>? getUserInfo() {
    var result = HiCache.getInstance().get(kUserInfo);
    if (result != null) {
      return jsonDecode(result);
    }
    return null;
  }

  static String? getBoardingPass() {
    var result = HiCache.getInstance().get(kUserInfo);
    if (result != null) {
      var map = jsonDecode(result);
      return map['boardingPass'];
    }
    return null;
  }

  static String? getAccountHash() {
    var result = HiCache.getInstance().get(kUserInfo);
    if (result != null) {
      var map = jsonDecode(result);
      return map['accountHash'].toString();
    }
    return null;
  }

  static void logout() {
    HiCache.getInstance().remove(kUserInfo);
    NavigatorUtil.go2LoginPage();
  }
}
